package com.property.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.property.biz.CommunityBiz;
import com.property.biz.ComplaintBiz;
import com.property.biz.HomemakeBiz;
import com.property.biz.LimitBiz;
import com.property.biz.LrrelationBiz;
import com.property.biz.ManagementBiz;
import com.property.biz.OwnerBiz;
import com.property.biz.ProvCityDistBiz;
import com.property.biz.UserBiz;
import com.property.entity.Community;
import com.property.entity.Homemake;
import com.property.entity.Limit;
import com.property.entity.Lrrelation;
import com.property.entity.Management;
import com.property.entity.Owner;
import com.property.entity.ProvCityDist;
import com.property.entity.Role;
import com.property.entity.User;

@Controller
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private CommunityBiz communityBiz;
	@Autowired
	private UserBiz userBiz;
	@Autowired
	private OwnerBiz ownerBiz;
	@Autowired
	private ComplaintBiz complaintBiz;
	@Autowired
	private ManagementBiz managementBiz;
	@Autowired
	private ProvCityDistBiz provCityDistBiz;
	@Autowired
	private LimitBiz limitBiz;
	@Autowired
	private LrrelationBiz lrrelationBiz;
	@Autowired
	private HomemakeBiz homemakeBiz;

	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		List<Community> list = communityBiz.getAll();// 小区列表
		request.setAttribute("communitys", list);

		List<Owner> owners = ownerBiz.getByStatus("已认证");// 已认证业主
		request.setAttribute("owners", owners);

		Date datetime = new Date();
		String time = (1900 + datetime.getYear()) + "-"
				+ (datetime.getMonth() + 1) + "-" + datetime.getDate();
		int dayLogin = userBiz.getLoginCount(time);// 当日登陆人数
		request.setAttribute("dayLogin", dayLogin);

		time = (1900 + datetime.getYear()) + "-" + (datetime.getMonth() + 1)
				+ "-1";
		int monthLogin = userBiz.getLoginCount(time);// 当月登陆人数
		request.setAttribute("monthLogin", monthLogin);

		int untreatedCount = complaintBiz.getUntreatedCount();// 报修未处理数量
		request.setAttribute("untreatedCount", untreatedCount);

		return "admin/index";
	}

	@RequestMapping("/communityList")
	public String communityList(String addressType, Integer province_code,
			Integer city_code, Integer area_code, String cname, Integer page,
			HttpServletRequest request) {
		page = page == null ? 1 : page;
		int pageSize = 11;
		int startIndex = (page - 1) * pageSize;
		Integer addressId = 0;
		if (area_code != null) {
			addressType = "2";
			addressId = area_code;
		} else if (city_code != null) {
			addressType = "1";
			addressId = city_code;
		} else if (province_code != null) {
			addressType = "0";
			addressId = province_code;
		}
		
		List<Management> countList = managementBiz.getCommunity(addressType,
				addressId, cname, 0, 999);// 用于记录总数量
		int count = (int) Math.ceil((double) countList.size() / pageSize);
		List<Management> communitys = managementBiz.getCommunity(addressType,
				addressId, cname, startIndex, pageSize);
		
		List<ProvCityDist> provList = provCityDistBiz.getProv("0");
		List<ProvCityDist> cityList = provCityDistBiz.getProv("1");
		List<ProvCityDist> distList = provCityDistBiz.getProv("2");

		request.setAttribute("page", page);
		request.setAttribute("count", count);

		request.setAttribute("communitys", communitys);
		for(Management management :communitys){
			System.out.println("aaaaaaa"+management.getCommunity().getStatus());
		}
		request.setAttribute("provList", provList);
		request.setAttribute("cityList", cityList);
		request.setAttribute("distList", distList);
			
		return "admin/communityList";
	}

	@RequestMapping("/register")
	public String register() {
		return "register";
	}

	@RequestMapping("/compilewrite")
	public String compilewritea(Model model, HttpSession session,
			String userName, String password) {

		return "admin/compilewrite";
	}
	
	@RequestMapping("/allManagement")
	public String allManagement(Model model){
		List<Management> list = managementBiz.getAll();
		model.addAttribute("manage", list);
		return "admin/allManagement";
	}

	@RequestMapping("/power")
	public String power(HttpServletRequest request,int id) {
		List<Limit> limits = limitBiz.getAll();
		List<Lrrelation> lrrelations = lrrelationBiz.getLimit(id);
		request.setAttribute("id", id);
		request.setAttribute("limits", limits);// 全部权限
		request.setAttribute("lrrelations", lrrelations);// 已有权限
		return "admin/power";
	}

	@RequestMapping("/setPower")
	public String setPower(HttpServletRequest request,
			HttpServletResponse response,int id) {
		List<Limit> limits = limitBiz.getAll();
		lrrelationBiz.delLimit(id);
		for (Limit limit : limits) {
			if ("on".equals(request.getParameter(limit.getName()))) {
				Lrrelation lrrelation =new Lrrelation();
				Limit limit2=new Limit();
				Management management=new Management();
				management.setId(id);
				limit2.setId(limit.getId());
				lrrelation.setLimit(limit2);
				lrrelation.setManagement(management);
				lrrelationBiz.setLimit(lrrelation);
			}
		}
		response.setContentType("text/html; charset=UTF-8"); // 转码
		

		List<Lrrelation> lrrelations = lrrelationBiz.getLimit(id);
		request.setAttribute("limits", limits);// 全部权限
		request.setAttribute("lrrelations", lrrelations);// 已有权限
		return "redirect:allManagement";
	}

	@RequestMapping(value = "/docompilewrite", method = RequestMethod.POST)
	public String compilewrite(Model model, HttpSession session, String name,
			String password, String email) {
		User user = (User) session.getAttribute("user");
		user.setUserName(name);
		user.setEmail(email);
		user.setPassWord(password);
		if (user.getUserName() == name) {
			userBiz.updateUser(user);
		} else {
			return "admin/compilewrite";
		}
		return "admin/index";
	}

	@RequestMapping("/adduserjsp")
	public String adduserjsp() {
		return "admin/adduser";
	}

	@RequestMapping(value = "/adduser", method = RequestMethod.POST)
	public String adduser(HttpServletResponse response, String name,
			String password, String email) {

		User user = new User();
		user.setUserName(name);
		user.setEmail(email);
		user.setPassWord(password);

		Role role = new Role();
		role.setId(3);
		user.setRole(role);

		userBiz.addUser(user);

//		response.setContentType("text/html; charset=UTF-8"); // 转码
//		try {
//			PrintWriter out = response.getWriter();
//			out.flush();
//			out.println("<script>");
//			out.println("alert('添加成功！');");
//			out.println("history.back();");
//			out.println("</script>");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return "redirect:/admin/index";

	}

	@RequestMapping(value="/homemakeList")
	public String dispose(Model model,HttpSession session,String name1,Integer id,Integer page){
		User user=(User) session.getAttribute("user");
		page = page == null ? 1 : page;    
		id = id == null ? 0 : id;    
        int pageSize =5;
 		int startIndex = (page - 1) * pageSize;
 		int rows = homemakeBiz.comCount(name1, id);
 		int pageCount = (int) Math.ceil((double) rows / pageSize);
		List<Homemake> homemakes = homemakeBiz.getHomemake(id,name1, startIndex, pageSize);
		model.addAttribute("homemakes", homemakes);
		model.addAttribute("totalPages", pageCount);
	    model.addAttribute("page", page);	
		return "admin/homemakeList";
	}
	


	@RequestMapping("/homemakedetail")
	public String ownerdetail(Homemake homemake, int id, Model model,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		homemake = homemakeBiz.getbyId(id);
		model.addAttribute("detail", homemake);
		return "admin/homemakedetail";
	}

	@RequestMapping("/delete")
	public String delete(int id) {
		homemakeBiz.delete(id);
		return "redirect:/admin/homemakeList";
	}

	@RequestMapping("/homemakeup")
	public String homemakeup(Integer id, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Homemake homemake = homemakeBiz.getbyId(id);
		model.addAttribute("id", id);
		model.addAttribute("detail", homemake);
		return "admin/homemakeup";
	}

	@RequestMapping(value = "/dohomemakeups", method = RequestMethod.POST)
	public String dohomemakeups(Homemake homemake) {
		homemakeBiz.updateHomemake(homemake);
		return "redirect:/admin/homemakeList";
	}

	@RequestMapping("/homemakeadd")
	public String homemakeadd(HttpSession session) {
		User user = (User) session.getAttribute("user");
		return "admin/homemakeadd";
	}

	@RequestMapping(value = "/dohomemakeadd", method = RequestMethod.POST)
	public String dohomemakeadd(Homemake homemake) {
		homemakeBiz.addHomemake(homemake);
		return "redirect:/admin/homemakeList";
	}

	@RequestMapping("/addmanagejsp")
	public String addmanagejsp(HttpServletRequest request) {
		List<Community> communities = communityBiz.getAll();
		request.setAttribute("communities", communities);
		return "admin/addmanage";
	}

	@RequestMapping("/addmanage")
	public String addmanage(HttpServletResponse response, String name,
			String password, String phone, String email, int communityid) {
		User user = new User();
		user.setUserName(name);
		user.setEmail(email);
		user.setPassWord(password);

		Role role = new Role();
		role.setId(2);
		user.setRole(role);

		Management management = new Management();
		management.setUser(user);
		management.setPhone(phone);

		Community community = new Community();
		community.setId(communityid);
		management.setCommunity(community);

		userBiz.addManageUser(user, management);

//		response.setContentType("text/html; charset=UTF-8"); // 转码
//		try {
//			PrintWriter out = response.getWriter();
//			out.flush();
//			out.println("<script>");
//			out.println("alert('添加成功！');");
//			out.println("history.back();");
//			out.println("</script>");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return "redirect:/admin/communityList";
	}

	@RequestMapping("/addcommunityjsp")
	public String addcommunityjsp(HttpServletRequest request) {
		List<ProvCityDist> provList = provCityDistBiz.getProv("0");
		List<ProvCityDist> cityList = provCityDistBiz.getProv("1");
		List<ProvCityDist> distList = provCityDistBiz.getProv("2");

		request.setAttribute("provList", provList);
		request.setAttribute("cityList", cityList);
		request.setAttribute("distList", distList);
		return "admin/addcommunity";
	}

	@RequestMapping("/addcommunity")
	public String addcommunity(HttpServletResponse response, String name,
			String phone, Integer area_code) {
		Community community = new Community();
		community.setCommunityName(name);
		community.setSecurityPhone(phone);
		community.setProvCityDistId(area_code);
		communityBiz.addCommunity(community);

//		response.setContentType("text/html; charset=UTF-8"); // 转码
//		try {
//			PrintWriter out = response.getWriter();
//			out.flush();
//			out.println("<script>");
//			out.println("alert('添加成功！');");
//			out.println("history.back();");
//			out.println("</script>");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}

		return "redirect:/admin/communityList";
	}
	
	@RequestMapping("/getCommunityById")
	@ResponseBody
	public Management getCommunityById(Integer id){
		Management management = managementBiz.getCommunityById(id);
		System.out.println(management);
		return management;
	}
	
	@RequestMapping("/delCommunity")
	public String delCommunity(int id){
		System.out.println(id);
		communityBiz.delCommunity(id);
		return "redirect:/admin/communityList";
	}
	
	
	@RequestMapping("/updateCom")
	public String updateCommunity(HttpSession session,Community community) throws IllegalStateException, IOException{
		

		String paString = session.getServletContext().getContextPath()+"\\statics\\images\\";
		
		System.out.println(paString);
		String sqlPath = null; 
		  //定义文件保存的本地路径
	      String localPath=session.getServletContext().getRealPath("statics\\images\\");
	      String localPathString="E:\\accp8.0\\Y2\\83T25_SSM\\property\\src\\main\\webapp\\statics\\images\\";
			
	      System.out.println(localPath);
	      //定义 文件名

	      String filename=null;  
	    
	          //生成uuid作为文件名称  
	          String uuid = UUID.randomUUID().toString().replaceAll("-",""); 
	          
	          
	          //获得文件类型（可以判断如果不是图片，禁止上传）  
	          String contentType=community.getFile().getContentType();  
	          
	          
	          //获得文件后缀名 
	          String suffixName=contentType.substring(contentType.indexOf("/")+1);
	          
	          //得到 文件名
	          filename=uuid+"."+suffixName; 
	          //文件保存路径
	          community.getFile().transferTo(new File(localPath+"\\"+filename));  
	          community.getFile().transferTo(new File(localPathString+"\\"+filename));
	      
	      //把图片的相对路径保存至数据库
	      
	      sqlPath = "/images/"+filename;
	      community.setCommunityImg(sqlPath);
		communityBiz.updateCommunity(community);
		System.out.println(sqlPath);
		return "redirect:communityList";
		
	}
	
	@RequestMapping("/getComId")
	@ResponseBody
	public Community getComId(int id){
		Community community=communityBiz.getById(id);
		return community;
		
	}
}
